<template>
  <view :data-theme="theme">
    <!-- 新增tab -->
    <u-tabs :list="tabList" :current="currentTab" @change="changeTab" lineColor="#8F4C38" lineWidth="70px"></u-tabs>
    <view
      class="content-container"
      @touchstart="onTouchStart"
      @touchmove="onTouchMove"
      @touchend="onTouchEnd"
    >
      <view
        class="tab-content"
        :style="{ transform: `translateX(${(dragOffset - currentTab * 100)}%)`, transition: dragTransition }"
      >
        <!-- 动态数据区域：待评论 -->
        <view class="tab-pane">
          <view class="my-order">
            <view class='list'>
              <view v-if="currentTab === 0">
                <view class='item' v-for="(item,index) in replyList" :key="index" style="padding-top: 5px;">
                  <view @click='goProDetails(item)' class='item-info acea-row row-between row-top'>
                    <view class='pictrue'>
<!--                      <easy-loadimage :image-src="item.image"></easy-loadimage>-->
                      <image class="origin-img" :src="item.image" mode="aspectFill"/>
                    </view>
                    <view class='text'>
                      <view class='title-row acea-row row-between'>
                        <view class='name line2'>{{ item.productName }}</view>
                        <view class='type'>{{ item.type === 0 ? '线下课' : '线上课' }}</view>
                      </view>
                      <view class='money'>
                        <view>￥{{ item.price }}</view>
                        <view>x{{ item.payNum }}</view>
                      </view>
                    </view>
                  </view>
                  <view class='bottom acea-row row-right row-middle'>
                    <view class='bnt bg_color' @click='evaluateTap(item)'>去评价</view>
                  </view>
                </view>
                <view class='loadingicon acea-row row-center-wrapper'>
                  <text class='loading iconfont icon-jiazai' :hidden='loading==false'></text>
                  {{ replyList.length > 0 ? loadTitle : '' }}
                </view>
                <emptyPage v-if="replyList.length == 0 && !loading" title="暂无评论~"
                           :imgSrc="urlDomain+'crmebimage/presets/noEvaluate.png'"></emptyPage>
              </view>
            </view>
          </view>
        </view>
        <!-- 动态数据区域：已评论 -->
        <view class="tab-pane">
          <view class="my-order">
            <view class='list'>
              <view v-if="currentTab === 1">
                <view class='item' v-for="(item,index) in repliedList" :key="index" style="padding-top: 5px;">
                  <view @click='goProDetails(item)' class='item-info acea-row row-between row-top'>
                    <view class='pictrue'>
<!--                      <easy-loadimage :image-src="item.image"></easy-loadimage>-->
                      <image class="origin-img" :src="item.image" mode="aspectFill"/>
                    </view>
                    <view class='text'>
                      <view class='title-row acea-row row-between'>
                        <view class='name line2'>{{ item.productName }}</view>
                        <view class='type'>{{ item.type === 0 ? '线下课' : '线上课' }}</view>
                      </view>
                      <view class="comment-rating">
                        <view class="star" v-for="n in (item.star || 5)" :key="n">★</view>
                        <view class="rating-score">{{ item.star || 5 }}分</view>
                      </view>
                    </view>
                  </view>
                  <view class="comment-content">
                    <img class="chapter-arrow-img" @click.stop="toggleExpand(index)" v-if="item.comment && item.comment.length > 50" :class="{ open:  item.isExpand }" src="https://fengqinghui.oss-cn-hangzhou.aliyuncs.com/monkey/monkey/zhanKaiMe.png" />
                    <view class="comment-bar"></view>
                    <view class="comment-text-wrapper">
                      <view
                        class="comment-text"
                        :class="{ 'slide-down': item.isExpand }"
                      >
                        {{ item.comment || '这条评论您只给打了评分呢' }}
                      </view>
                      <view v-for="(ite,ind) in item.pics" :key="ind" style="width: 40px;height: 40px;display: inline-block;margin-right: 10rpx" >
                        <image :src="ite" style="width: 100%;height: 100%" mode="aspectFill" @click="previewCommentImage(ite)"></image>

                      </view>
                    </view>
                  </view>
                  <view class='bottom acea-row row-right row-middle'>
                    <view class='btn-delete' @click="deleteComment(item)">删除</view>
                  </view>
                </view>
                <view class='loadingicon acea-row row-center-wrapper'>
                  <text class='loading iconfont icon-jiazai' :hidden='loading2==false'></text>
                  {{ repliedList.length > 0 ? loadTitle2 : '' }}
                </view>
                <emptyPage v-if="repliedList.length == 0 && !loading2" title="暂无已评论~"
                           :imgSrc="urlDomain+'crmebimage/presets/noEvaluate.png'"></emptyPage>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <view v-if="showImgPreview" class="img-preview-mask" @click="closeImgPreview">
      <image
        :src="previewImgUrl" mode="widthFix"
        :class="['img-preview', imgPreviewClosing ? 'img-preview-animate-leave' : 'img-preview-animate']"
        @click.stop
      ></image>
      <view class="img-preview-close" @click.stop="closeImgPreview">×</view>
    </view>
  </view>
</template>

<script>
import {
  orderReplyList,
  orderReplyCommentedList
} from '@/api/order.js';
import {toLogin} from '@/libs/login.js';
import {mapGetters} from "vuex";
import emptyPage from '@/components/emptyPage.vue'
import easyLoadimage from '@/components/base/easy-loadimage.vue';
import {goProductDetail} from "../../../libs/order";
import {deleteReply} from "../../../api/order";

const app = getApp();
export default {
  data() {
    return {
      urlDomain: this.$Cache.get("imgHost"),
      loading: false, //是否加载中
      loadend: false, //是否加载完毕
      loading2: false, //是否加载中
      loadend2: false, //是否加载完毕
      loadTitle: '显示更多', //提示语
      loadTitle2: '显示更多', //提示语
      replyList: [], //订单数组
      repliedList: [], // 新增已评论数据
      page: 1,
      page2: 1,
      limit: 20,
      isShow: false,
      theme: app.globalData.theme,
      tabList: [
        { name: '待评论' },
        { name: '已评论' }
      ],
      currentTab: 0,
      // 滑动相关
      startX: 0,
      dragOffset: 0,
      dragTransition: 'transform 0.3s ease',
      threshold: 50,
      showImgPreview: false,
      previewImgUrl: '',
      imgPreviewClosing: false,
    };
  },
  computed: mapGetters(['isLogin']),
  components: {
    emptyPage,
    easyLoadimage
  },
  // 滚动监听
  onPageScroll(e) {
    // 传入scrollTop值并触发所有easy-loadimage组件下的滚动监听事件
    uni.$emit('scroll');

  },
  onShow() {
    uni.setNavigationBarTitle({
      title: '评价列表'
    })
    let that = this;
    if (this.isLogin) {
      this.loadend = false;
      this.page = 1;
      this.$set(this, 'replyList', []);
      this.getReplyList();
      this.loadend2 = false;
      this.page2 = 1;
      this.$set(this, 'repliedList', []);
      this.getReplyCommentedList();
    } else {
      toLogin();
    }
  },
  // watch:{
  //   currentTab(newVal, oldVal) {
  //     console.log('count 变化：', newVal, oldVal);
  //     if(){}
  //   },
  // },
  methods: {
    returns() {
      uni.navigateBack()
    },
    evaluateTap(item) {
      uni.navigateTo({
        url: "/pages/goods/goods_comment_con/index?orderNo=" + item.orderNo + "&id=" + item.id
      })
    },
    /**
     * 去商品详情productType，商品类型:0-普通，1-秒杀，2-砍价，3-拼团，4-视频号
     */
    goProDetails: function (item) {
      // goProductDetail(item.productId, 0, `&typeNum=${item.productType}`)
      console.log(item.productId)
      uni.navigateTo({
        url: '/pages/discover/courseDetails/index?id=' + item.productId
      })
    },
    /**
     * 获取订单列表
     */
    getReplyList: function () {
      let that = this;
      if (that.loadend) return;
      if (that.loading) return;
      that.loading = true;
      that.loadTitle = '显示更多';
      orderReplyList({
        page: that.page,
        limit: that.limit,
      }).then(res => {
        let list = res.data.list || [];
        let loadend = list.length < that.limit;
        that.replyList = that.$util.SplitArray(list, that.replyList);
        that.$set(that, 'replyList', that.replyList);
        that.loadend = loadend;
        that.loading = false;
        that.loadTitle = loadend ? "" : '显示更多';
        that.page = that.page + 1;
        that.isShow = true;
      }).catch(err => {
        that.loading = false;
        that.loadTitle = '显示更多';
      })
    },
    /**
     * 获取已评论订单列表
     */
    getReplyCommentedList: function () {
      let that = this;
      if (that.loadend2) return;
      if (that.loading2) return;
      that.loading2 = true;
      that.loadTitle2 = '显示更多';
      orderReplyCommentedList({
        page: that.page2,
        limit: that.limit,
      }).then(res => {
        let list = res.data.list || [];
        let loadend2 = list.length < that.limit;
        that.repliedList = that.$util.SplitArray(list, that.repliedList);
        that.$set(that, 'repliedList', that.repliedList);
        // 假设 this.repliedList 是原始数组
        that.repliedList = that.repliedList.map(item => {
          // 复制原对象，避免直接修改
          const newItem = { ...item };
          // 将 pics 字符串按逗号分隔成数组（如果 pics 存在）
          if (newItem.pics) {
            newItem.pics = newItem.pics.split(',');
          }
          return newItem;
        });

// 示例：
// 原数据：[{ id: 1, pics: "a.jpg,b.jpg" }]
// 转换后：[{ id: 1, pics: ["a.jpg", "b.jpg"] }]
        that.loadend2 = loadend2;
        that.loading2 = false;
        that.loadTitle2 = loadend2 ? "" : '显示更多';
        that.page2 = that.page2 + 1;
        that.isShow = true;
      }).catch(err => {
        that.loading2 = false;
        that.loadTitle2 = '显示更多';
      })
    },
    changeTab(e) {
      this.currentTab = e.index;
    },
    // 滑动手势处理
    onTouchStart(e) {
      this.startX = e.touches[0].clientX;
      this.lastTouchX = e.touches[0].clientX;
      this.touchStartTime = Date.now();
      this.dragOffset = 0;
      this.dragTransition = 'none';
      this.touchMoves = [];
    },
    onTouchMove(e) {
      const moveX = e.touches[0].clientX - this.startX;
      const windowWidth = uni.getSystemInfoSync().windowWidth;
      // 记录触摸移动轨迹（用于防抖）
      this.touchMoves.push(moveX);
      if (this.touchMoves.length > 5) this.touchMoves.shift();
      // 防抖判断：如果最近5次移动距离变化不大，视为抖动，直接返回
      if (this.touchMoves.length >= 5 && Math.abs(this.touchMoves[4] - this.touchMoves[0]) < 10) {
        return;
      }
      // 增加最小移动阈值，避免轻微触碰触发
      const threshold = 60;
      if (Math.abs(moveX) < threshold) return;
      // 计算拖动百分比
      let dragPercentage = (moveX / windowWidth) * 100;
      // 禁止边界拖动
      if ((this.currentTab === 0 && dragPercentage > 0) || (this.currentTab === this.tabList.length - 1 && dragPercentage < 0)) {
        dragPercentage = 0;
      }
      this.dragOffset = dragPercentage;
    },
    onTouchEnd() {
      const windowWidth = uni.getSystemInfoSync().windowWidth;
      const moveX = this.dragOffset * windowWidth / 100;
      const touchDuration = Date.now() - this.touchStartTime;
      const touchDistance = Math.abs(moveX);
      // 计算滑动速度（像素/毫秒）
      const swipeSpeed = touchDistance / touchDuration;
      // 确保动画时间一致
      const animationDuration = 300;
      this.dragTransition = `transform ${animationDuration}ms cubic-bezier(0.0, 0.0, 1.0, 1.0)`;
      // 动态阈值计算（根据滑动速度调整，速度越快阈值越低）
      const baseThreshold = windowWidth / 5;
      const speedFactor = Math.min(1, swipeSpeed * 2);
      const dynamicThreshold = baseThreshold * (1 - speedFactor * 0.5);
      // 快速滑动判断
      const isQuickSwipe = (touchDuration < 300 && touchDistance > windowWidth * 0.1) || (swipeSpeed > 0.5);
      let targetTab = this.currentTab;
      if ((moveX > dynamicThreshold && this.currentTab > 0) || (isQuickSwipe && moveX > 0 && this.currentTab > 0)) {
        targetTab--;
      } else if ((moveX < -dynamicThreshold && this.currentTab < this.tabList.length - 1) || (isQuickSwipe && moveX < 0 && this.currentTab < this.tabList.length - 1)) {
        targetTab++;
      }
      targetTab = Math.max(0, Math.min(this.tabList.length - 1, targetTab));
      if (targetTab !== this.currentTab) {
        this.currentTab = targetTab;
      }
      setTimeout(() => {
        this.dragOffset = 0;
        this.dragTransition = 'none';
      }, animationDuration);
    },
    deleteComment(item) {
      uni.showModal({
        title: '提示',
        content: '确定要删除此评论吗？',
        success: (res) => {
          if (res.confirm) {
            // 调用删除接口
            deleteReply(item.id).then(res => {
              this.repliedList = this.repliedList.filter(
                  (element) => element.id !== item.id
              );
              uni.showToast({
                title: '删除成功',
                icon: 'none'
              });
            }).catch(err => {
              uni.showToast({
                title: err.msg || '删除失败',
                icon: 'none'
              });
            });
          }
        }
      });
    },
    toggleExpand(index) {
      this.repliedList[index].isExpand = !this.repliedList[index].isExpand;
      this.$forceUpdate();
    },
    previewCommentImage(url) {
      this.previewImgUrl = url;
      this.showImgPreview = true;
      this.imgPreviewClosing = false;
    },
    closeImgPreview() {
      this.imgPreviewClosing = true;
      setTimeout(() => {
        this.showImgPreview = false;
        this.previewImgUrl = '';
        this.imgPreviewClosing = false;
      }, 280);
    }
  },
  onReachBottom: function () {
    if(this.currentTab === 0){
      this.getReplyList();
    } else {
      this.getReplyCommentedList();
    }
  }
}
</script>

<style scoped lang="scss">
.chapter-arrow-img {
  width: 18px;
  height: 18px;
  margin-right: 6px;
  transition: transform 0.2s;
  display: inline-block;
  transform: rotate(180deg);
  &.open {
    transform: rotate(360deg);
  }
}
.sku {
  font-size: 24rpx;
  color: #999999;
  margin: 10rpx 0;
}

.icon-shangjiadingdan {
  font-size: 28rpx;
}

.icon-xiangyou {
  font-size: 10rpx;
}

.my-order .header {
  height: 250rpx;
  padding: 0 30rpx;
}

.my-order .header .picTxt {
  height: 190rpx;
}

.my-order .header .picTxt .text {
  color: rgba(255, 255, 255, 0.8);
  font-size: 26rpx;
  font-family: 'Guildford Pro';
}

.my-order .header .picTxt .text .name {
  font-size: 34rpx;
  font-weight: bold;
  color: #fff;
  margin-bottom: 20rpx;
}

.my-order .header .picTxt .pictrue {
  width: 122rpx;
  height: 109rpx;
}

.my-order .header .picTxt .pictrue image {
  width: 100%;
  height: 100%;
}

.my-order .nav {
  background-color: #fff;
  border-top: 1px solid #F5F5F5;
  // margin: -60rpx 0 0;

}

.my-order .nav .item {
  text-align: center;
  font-size: 26rpx;
  color: #282828;
  padding: 26rpx 30rpx;
  display: inline-block;
  background-color: #fff;
}

.my-order .nav .item.on {
  /* #ifdef H5 || MP */
  font-weight: bold;
  /* #endif */
  /* #ifdef APP-PLUS */
  color: #000;
  /* #endif */
  position: relative;
}

.my-order .nav .item.on ::after {
  content: '';
  width: 78rpx;
  height: 4rpx;
  @include main_bg_color(theme);
  position: absolute;
  bottom: 2rpx;
  left: 30rpx;
}

.my-order .nav .item .num {
  margin-top: 18rpx;
}

.my-order .list {
  width: 100vw;
  margin: 0;
  padding: 0 14rpx;
}

.my-order .list .item {
  background-color: #fff;
  border-radius: 14rpx;
  margin-bottom: 14rpx;
}

.my-order .list .item .title {
  height: 84rpx;
  padding: 0 24rpx;
  border-bottom: 1rpx solid #eee;
  font-size: 28rpx;
  color: #282828;
}

.my-order .list .item .title .sign {
  font-size: 24rpx;
  padding: 0 13rpx;
  height: 36rpx;
  margin-right: 15rpx;
  border-radius: 18rpx;
  @include coupons_border_color(theme);
  @include main_color(theme);
}

.my-order .list .item .item-info {
  padding: 0 24rpx;
  margin-top: 22rpx;
}

.my-order .list .item .item-info .pictrue {
  width: 120rpx;
  height: 120rpx;
  .origin-img {
    width: 90%;
    height: 90%;
  }
}

.my-order .list .item .item-info .pictrue image, ::v-deep .easy-loadimage, uni-image {
  width: 100%;
  height: 100%;
  border-radius: 14rpx;
}

.my-order .list .item .item-info .text {
  width: 500rpx;
  font-size: 28rpx;
  color: #999;
}

.my-order .list .item .item-info .text .name {
  width: 350rpx;
  color: #282828;
}

.my-order .list .item .item-info .text .money {
  text-align: right;
}

.font_color {
  @include main_color(theme);
}

.my-order .list .item .totalPrice {
  font-size: 26rpx;
  color: #282828;
  text-align: right;
  margin: 27rpx 0 0 30rpx;
  padding: 0 30rpx 30rpx 0;
  border-bottom: 1rpx solid #eee;
}

.my-order .list .item .totalPrice .money {
  font-size: 28rpx;
  font-weight: bold;
  @include price_color(theme);
}

.my-order .list .item .bottom {
  height: 107rpx;
  padding: 0 30rpx;
}

.my-order .list .item .bottom .bnt {
  // width: 176rpx;
  height: 60rpx;
  text-align: center;
  line-height: 60rpx;
  @include main_color(theme);
  border-radius: 50rpx;
  font-size: 27rpx;
  padding: 0 30rpx;
  @include coupons_border_color(theme);
}

.my-order .list .item .bottom .bnt.cancelBnt {
  border: 1rpx solid #ddd;
  color: #aaa;
}

.my-order .list .item .bottom .bnt ~ .bnt {
  margin-left: 17rpx;
}

.noCart {
  margin-top: 171rpx;
  padding-top: 0.1rpx;
}

.noCart .pictrue {
  width: 414rpx;
  height: 336rpx;
  margin: 78rpx auto 56rpx auto;
}

.noCart .pictrue image {
  width: 100%;
  height: 100%;
}

::v-deep .tui-red {
  @include main_bg_color(theme);
}

::v-deep .tui-red-outline {
  @include main_color(theme);
  @include coupons_border_color(theme);
}
.content-container {
  width: 100vw;
  height: calc(100vh - 100rpx);
  overflow: hidden;
  position: relative;
  .tab-content {
    display: flex;
    height: 100%;
    // 不设置width: 200vw;
  }
  .tab-pane {
    flex-shrink: 0;
    width: 100vw;
    height: 100%;
    overflow-y: auto;
    display: flex;
    flex-direction: column;
    align-items: center;
  }
}
.comment-content {
  display: flex;
  align-items: flex-start;
  margin: 12rpx 0 0 0;
  padding: 0;
  background: none;
  box-shadow: none;
  border-radius: 0;
  .comment-icon {
    display: none;
  }
  .comment-bar {
    width: 6rpx;
    height: 38rpx;
    background: #e0b080;
    border-radius: 3rpx;
    margin-right: 16rpx;
    margin-top: 4rpx;
    flex-shrink: 0;
  }
  .comment-text {
    color: #666;
    font-size: 26rpx;
    line-height: 1.7;
    word-break: break-all;
    flex: 1;
    font-style: normal;
  }
}
.comment-text-wrapper {
  position: relative;
}
.comment-text {
  max-height: 84rpx;
  overflow: hidden;
  transition: all 0.4s cubic-bezier(.55,0,.1,1);
}
.comment-text.slide-down {
  max-height: 1000px;
}
.expand-btn {
  color: #8F4C38;
  font-size: 24rpx;
  margin-top: 8rpx;
  cursor: pointer;
}
.title-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 6rpx;
}
.type {
  color: #8e4c38;
  font-size: 26rpx;
  margin-left: 16rpx;
  white-space: nowrap;
}
.comment-rating {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin: 8rpx 0 0 0;
  .star {
    color: #FFD700;
    font-size: 28rpx;
    margin-right: 2rpx;
  }
  .rating-score {
    color: #FF9900;
    font-size: 24rpx;
    margin-left: 8rpx;
  }
}
.btn-delete {
  background: none;
  border: 1rpx solid #E53935;
  color: #E53935;
  font-weight: 600;
  border-radius: 44rpx;
  font-size: 30rpx;
  padding: 0 36rpx;
  height: 60rpx;
  line-height: 60rpx;
  transition: background 0.2s, color 0.2s;
}
.btn-delete:active {
  background: #fbeee6;
}
.img-preview-mask {
  position: fixed;
  left: 0; top: 0; right: 0; bottom: 0;
  background: rgba(0,0,0,0.7);
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
}
.img-preview {
  max-width: 80vw;
  min-height: 80vw;
  border-radius: 8px;
  box-shadow: 0 4px 24px rgba(0,0,0,0.3);
}
.img-preview-close {
  position: fixed;
  top: 40rpx;
  right: 40rpx;
  font-size: 60rpx;
  color: #fff;
  z-index: 10000;
  font-weight: bold;
  cursor: pointer;
}
@keyframes img-pop-in {
  0% {
    opacity: 0;
    transform: scale(0.7);
  }
  100% {
    opacity: 1;
    transform: scale(1);
  }
}
@keyframes img-pop-out {
  0% {
    opacity: 1;
    transform: scale(1);
  }
  100% {
    opacity: 0;
    transform: scale(0.7);
  }
}
.img-preview-animate {
  animation: img-pop-in 0.28s cubic-bezier(.55,0,.1,1);
}
.img-preview-animate-leave {
  animation: img-pop-out 0.28s cubic-bezier(.55,0,.1,1);
}
</style>

